<?php

use yii\helpers\Html;
use yii\helpers\ArrayHelper;
use yii\helpers\Url;
use yii\widgets\ActiveForm;
use backend\modules\supplier\models\Factory;
use backend\modules\supplier\models\PurchaseIn;
use backend\modules\supplier\models\PurchaseInDetailSearch;

/* @var $this yii\web\View */
/* @var $model backend\modules\supplier\models\PurchaseIn */
/* @var $form yii\widgets\ActiveForm */

$def = [0 => '不选择'];
$t = ArrayHelper::map(Factory::getAll(), 'id', 'name');
$factorys = array_merge($def, $t);

$status=[PurchaseIn::STATUS_UNAUDIT=>'未审核',PurchaseIn::STATUS_AUDITED=>'已审核'];

?>

<div class="purchase-in-form">
    
    <?php $form = ActiveForm::begin(); ?>

    <div class="well">
        <div class="row">
            <div class="col-sm-6">
                <div class="row">
                    <div class="col-sm-12"><?= $form->field($model, 'sn')->textInput(['maxlength' => 15,'readonly'=>true]) ?></div>
                </div>
                <div class="row">
                    <div class="col-sm-4"><?= $form->field($model, 'factory_id')->dropDownList($factorys) ?></div>
                    <div class="col-sm-4"><?= $form->field($model, 'remark')->textInput() ?></div>
                    <div class="col-sm-4"><?= $form->field($model, 'status')->radioList($status) ?></div>
                </div>
            </div>
            <div class="col-sm-6">
                <div class="row">
                    <div class="col-sm-3"><?= $form->field($model, 'add_name')->textInput(['readonly'=>true]) ?></div>
                    <div class="col-sm-3"><?= $form->field($model, 'add_time')->textInput(['readonly'=>true]) ?></div>
                    <div class="col-sm-3"><?= $form->field($model, 'chk_name')->textInput(['readonly'=>true]) ?></div>
                    <div class="col-sm-3"><?= $form->field($model, 'chk_date')->textInput(['readonly'=>true]) ?></div>
                </div>
                <div class="row">
                    <div class="col-sm-6"><?= $form->field($model, 'total_price')->textInput(['maxlength' => 10,'readonly'=>true]) ?></div>
                    <div class="col-sm-6"><?= $form->field($model, 'total_price_in')->textInput(['maxlength' => 10,'readonly'=>true]) ?></div>
                    <div class="col-sm-4 none"><?= $form->field($model, 'total_paid')->textInput(['maxlength' => 10,'readonly'=>true]) ?></div>
                </div>

                <div class="row none">
                    <div class="col-sm-6"><?= $form->field($model, 'pay_name')->textInput() ?></div>
                    <div class="col-sm-6"><?= $form->field($model, 'pay_date')->textInput() ?></div>
                </div>
            </div>
        </div>
    </div>
    
    <div class="row">
        <div class="col-sm-6"><h4 style="font-weight:bold;">货品列表</h4></div>
        <div class="col-sm-6" style="text-align: right;height:100%">
            <div class="btn-group">
                <button type="button" class="btn btn-default" onclick="listImg(this);">显示图片</button>
                <button type="button" class="btn btn-default" onclick="$('#purchaseInDetail').kitt2000Bill('createRow');">新增一行</button>
            </div>
        </div>
    </div>
    
    
    <?php
    $searchModel = new PurchaseInDetailSearch();
    
    echo kitt2000\bill\Bill::widget([
        'id'=>'purchaseInDetail',
        'focusIndex'=>['product_sn','number',['price','select'=>true]],
        'countField'=>['number','count'],
        'getProductUrl'=>['/goods/product/get-info-by-sn'],
        'dataProvider' => $searchModel->search(['purchaseInDetailSearch'=>['master_id'=>$model->id]]),
        'columns' => [
            ['class' => 'kitt2000\bill\SerialColumn'],
            [
                'header' => '图片',
                'options' => ['class' => 'img none'],
                'headerOptions'=>['class' => 'img none'],
                'contentOptions'=>['class' => 'img none'],
                'footerOptions'=>['class' => 'img none'],
                'content' => [
                    'thumb' => ['tag' => 'img','value'=>'$data->product->img','options'=>['width' => 40, 'height' => 40]],
                    'id' => ['tag' => 'input','type'=>'hidden','name'=>'PurchaseIn[detail][][id]','value'=>'$data->id'],
                ],
            ],
            'goods_name',
            [
                'header' => '厂家编码',
                'content' => [
                    'sn_purchase' => ['tag' => 'text','value'=>'$data->product->sn_purchase'],
                ],
            ],
            [
                'header' => '库存',
                'content' => [
                    'number_stock' => ['tag' => 'text','value'=>'$data->product->number_stock'],
                ],
            ],
            [
                'header' => '货位',
                'content' => [
                    'slot' => ['tag' => 'text','value'=>'$data->product->slot'],
                ],
            ],
            [
                'header' => '货品编号 <span class="red">*</span>',
                'content' => [
                    'product_sn' => ['tag' => 'input','type'=>'text','name'=>'PurchaseIn[detail][][product_sn]','value'=>'$data->product_sn'],
                ],
            ],
            [
                'header' => '数量 <span class="red">*</span>',
                'content' => [
                    'number' => ['tag' => 'input', 'type' => 'text','name'=>'PurchaseIn[detail][][number]','value'=>'$data->number', 'options' => ['class' => 'format-number require',]]
                ],
            ],
            [
                'header' => '价格 <span class="red">*</span>',
                'content' => [
                    'price' => ['tag' => 'input', 'type' => 'text','name'=>'PurchaseIn[detail][][price]','value'=>'$data->price', 'options' => ['class' => 'format-money require',]]
                ],
            ],
            [
                'header' => '小计',
                'content' => [
                    'count' => ['tag' => 'formula','value'=>'$data->number*$data->price','expression'=>'{number}*{price}']
                ],
            ],
            [
                'header' => '备注',
                'content' => [
                    'remark' => ['tag' => 'input', 'type' => 'text','name'=>'PurchaseIn[detail][][remark]']
                ],
            ],
            [
                'class' => 'kitt2000\bill\ActionColumn',
            ],
        ],
    ]);
    ?>

    <div class="form-group">
        <?= Html::button($model->isNewRecord ? '新建' : '更新', ['class' => $model->isNewRecord ? 'btn btn-success' : 'btn btn-primary']) ?>
    </div>

    <?php ActiveForm::end(); ?>

</div>

<script>
    window.onload = function () { 
        form_beforeSubmit();
        format_init();
        del_onclick();
    };
    
    function del_onclick(){
        $('#bill .del').click(function(){
            alert('del');
        });
    }

    function listImg(e) {
        var status=$(e).attr('status');
        var target='#purchaseInDetail .img';

        if (status==undefined || status=='0') {
            $(target).removeClass('none');
            $(e).html('隐藏图片');
            newStatus=1;
        } else {
            $(target).addClass('none');
            $(e).html('显示图片');
            newStatus=0;
        }
        $(e).attr('status',newStatus);
    }

    function form_beforeSubmit() {
        $('#<?= $form->getId() ?>').on('beforeSubmit', function () {
            var isBreak = false;
            
            $('#<?= $form->getId() ?> tr.item').each(function(){
                if($(this).find('.sn')==''){
                    $(this).remove();
                }
                
                $(this).find('.require').each(function(){
                    if ($.trim($(this).val()) == '') {
                        alert('必填项为空！');
                        $(this).focus();
                        isBreak = true;
                    }
                });
            });
            
            return isBreak == false ? true : false;
        });
    }
    
    function getProductInfo(e){
        if (event.keyCode != 13){
            return false;
        }
        
        var val=$.trim($(e).val());
        if(val!==''){
            //检查是否重复
            var isBreak=false;
            $('#bill .sn').each(function(){
                if(e!==this && val==$(this).val()){
                    $(this).focus();
                    $(e).val('');
                    isBreak=true;
                }
            });
            
            if(isBreak==true){
                return false;
            }
            
            var url='<?=  Url::to(['get-product-by-sn']);?>';
            $.getJSON(url,{'sn':val},function(ret){
                if(ret.result==false){
                    $(e).val('');
                    alert(ret.content.msg);
                }else{
                    var tr=$(e).parent().parent();
                    setProductInfo(tr,ret.content.product);
                    $(tr).find('.number').focus();
                }
            });
        }
    }
    
    function setProductInfo(tr,info){
        $(tr).find('img.img').attr('src',info.img);
        $(tr).find('td.name').html(info.name);
        $(tr).find('td.sn_purchase').html(info.sn_purchase);
        $(tr).find('td.stock').html(info.stock);
        $(tr).find('td.slot').html(info.slot);
        $(tr).find('.price').val(info.price);
    }
    
    function setPrice(e){
        if (event.keyCode == 13){
            var tr=$(e).parent().parent();
            $(tr).find('.price').select();
            count(e);
        }
    }
    
    function createNew(e){
        event.keyCode == 13 && newRow(e);
    }
    
    function newRow(e){
        var bill = $.fn.bill.getObj("bill");
        bill && bill.newRow();
        count(e);
        format_init();
    }
    
    function del(e){
        var tr=$(e).parent().parent();
        tr.remove();
        totalCount();
        var bill = $.fn.bill.getObj("bill");
        bill && bill.serial();
    }
    
    function count(e){
        var tr=$(e).parent().parent();
        var price=parseFloat($(tr).find('.price').val());
        var number=parseInt($(tr).find('.number').val());
        $(tr).find('.count').html(price*number);
        
        totalCount();
    }
    
    function totalCount(){
        var countNum=allCount=0;
        $('#bill tr.item').each(function(){
            var number=$(this).find('.number').val()=='' ? 0:parseInt($(this).find('.number').val());
            var price=$(this).find('.price').val()=='' ? 0: parseFloat($(this).find('.price').val());
            countNum+=number;
            allCount+=number*price;
        });

        $('#bill').find('.all-count .num').html(countNum);
        $('#bill').find('.all-count .count').html(allCount);
    }
    
</script>
